<?php
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUpdate.php';

	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoUser.php';
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoFavourite.php';
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoItem.php';
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoProvider.php';
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoUpdate.php';
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/daoCoupleInvitation.php';
	
	require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/couple_invitation.php';
	
	class UserBus {
		private $_userDao;
		private $_favDao;	
		private $_itemDao;
		private $_providerDao;
		private $_updateDao;
		private $_coupleInvitationDao;
		
		private $_updateBus;
		
		public function __construct() {
			$this->_userDao = new UserDao();
			$this->_favDao = new FavouriteDao();
			$this->_itemDao = new ItemDao();
			$this->_providerDao = new ProviderDao();
			$this->_updateDao = new UpdateDao();
			$this->_coupleInvitationDao = new CoupleInvitationDao();
			
			$this->_updateBus = new UpdateBus();
		}
		
		// strip contents having special html character to avoid XSS 
		private function prepareUserModel($user) {
			$user->setBlast(GeneralFunctions::stripString($user->getBlast()));
			$user->setCellPhone(GeneralFunctions::stripString($user->getCellPhone()));
			$user->setDateOfBirth(GeneralFunctions::stripString($user->getDateOfBirth()));
			$user->setEmail(GeneralFunctions::stripString($user->getEmail()));
			$user->setFirstName(GeneralFunctions::stripString($user->getFirstName()));
			$user->setGender(GeneralFunctions::stripString($user->getGender()));
			$user->setLastName(GeneralFunctions::stripString($user->getLastName()));
			$user->setPasswordHash(GeneralFunctions::stripString($user->getPasswordHash()));
			$user->setTelephone(GeneralFunctions::stripString($user->getTelephone()));
			$user->setUserName(GeneralFunctions::stripString($user->getUserName()));
			$user->setCoupleUserName(GeneralFunctions::stripString($user->getCoupleUserName()));
			$user->setCoupleNickName(GeneralFunctions::stripString($user->getCoupleNickName()));
			$user->setMariageStatus(GeneralFunctions::stripString($user->getMariageStatus()));
			
			return $user;
		}
		
		// check if a username is not in the list not allowed username
		public function isUserNameAllowed($username) {
			global $ubi;
			return !in_array($username, $ubi['SITE']['USERNAMES_NOT_ALLOWED']);	
		}
		
		public function addUser($user) {
			global $ubi;
			global $ubi_score;
			
			$user->setRoleID($ubi['ROLE']['DEFAULT']);			
			
			$id = $this->_userDao->addUser($this->prepareUserModel($user));
			if ($id) {
				$this->addScore($id, $ubi_score['REGISTER']);
			}
			
			return $id;
		}
		
		public function getUser($userID) {
			return $this->_userDao->getUser($userID);
		}
		
		public function login($username, $password, $ipAddress) {
			global $ubi_score;
			
			$user = $this->_userDao->login($username, $password);
			if ($user) {
				$this->addScore($user->getUserID(), $ubi_score['LOGIN']);
				$lastLogin = $user->getLastLogin();
				$currentTime =  $_SERVER['REQUEST_TIME'];
				$diffTime = $currentTime - $lastLogin;
				$hour = date('H', $diffTime);
				if ($hour < 12) {
					$this->addScore($user->getUserID(), $ubi_score['LOGIN_12']);
				} else if ($hour < 24) {
					$this->addScore($user->getUserID(), $ubi_score['LOGIN_24']);
				} else if ($hour < 48) {
					$this->addScore($user->getUserID(), $ubi_score['LOGIN_48']);
				}
				$this->_userDao->updateLastLoginAndIPAddress($user->getUserID(), $ipAddress);
			}
			
			return $user;
		}
		
		public function isExistedByUserName($username) {
			return $this->_userDao->isExistedByUserName($username);			
		}
		
		public function isExistedByEmail($email) {
			return $this->_userDao->isExistedByEmail($email);			
		}
		
		public function isExistedByUserId($userId) {
			return $this->_userDao->isExistedByUserId($userId);			
		}
		
		public function updateUser($user)	{
			return $this->_userDao->updateUser($this->prepareUserModel($user));
		}
		
		//function used to activate user with the code passed in
		public function activateUser($code) {
			return $this->_userDao->activateUser(strtolower($code));
		}		
		
		public function updateBlast($content, $userid) {
			global $ubi;
			$content = GeneralFunctions::stripString($content);
			$ck = $this->_userDao->updateBlast($content, $userid);
			if ($ck == 1) {
				$update = new UpdateModel();
				$update->setIndicteeID($userid);
				$update->setModifiedDate($_SERVER['REQUEST_TIME']);
				$update->setUpdateType($ubi['UPDATE']['BLAST']);
				$update->setUserID($userid);
				$update->setLink('index.php?view&type=user&userid=' . $userid);
				
				$cont = substr($content, 0, $ubi['SITE']['SHORT_BLAST']);
				if (strlen($cont) < strlen($content)) {
					$cont .= '...';
				}
				$update->setName($cont);
				
				$this->_updateDao->addUpdate($update);
			}
			return $ck;
		}
		
		public function getUserListByUserIdList($idList) {
			$userList = array();
			for ($i = 0; $i < count($idList); $i++) {
				$userList[$idList[$i]] = $this->_userDao->getUser($idList[$i]);
			}
			return $userList;			
		}
		
		public function getUserByUserName($userName) {
			return $this->_userDao->getUserByUserName($userName);
		}
		
		public function isEmailExisted($email){
			return $this->_userDao->isEmailExisted($email);
		}
		
		public function getUserByToken($token) {
			return $this->_userDao->getUserByToken($token);
		}
		
		public function getUserByEmail($email) {
			return $this->_userDao->getUserByEmail($email);
		}
		
		public function updateToken($user) {
			return $this->_userDao->updateToken($user);
		}
		
		public function updatePassword($user)	{			
			return $this->_userDao->updatePassword($user);
		}
		
		public function getFavouriteItems($userID) {
			global $ubi;
			
			$favList = $this->_favDao->getFavouritesOfUser($userID, $ubi['ITEM']['VALUE']);
			if (isset($favList)) {
				$itemList = array();
							
				for ($i = 0; $i < count($favList); $i++) {
					$fav = $favList[$i];
	
					$item = $this->_itemDao->getItem($fav->getIndicteeID());
					if ($item) {
						$itemList[] = $item;
					}					
				}				
			}
			
			return $itemList;
		}
		
		public function getFavouriteProviders($userID) {
			global $ubi;
			
			$favList = $this->_favDao->getFavouritesOfUser($userID, $ubi['PROVIDER']['VALUE']);
			if (isset($favList)) {
				$providerList = array();
				for ($i = 0; $i < count($favList); $i++) {
					$fav = $favList[$i];
					$provider = $this->_providerDao->getProvider($fav->getIndicteeID());
					$providerList[] = $provider;					
				}				
			}
			
			return $providerList;
		}
		
		public function getBestUsers() {
			return $this->_userDao->getBestUsers();
		}
		
		public function getNumberOfUser() { 
			return $this->_userDao->getNumberOfUser();
		}
		
		public function getNumberProviderPost($userID) {
			return $this->_userDao->getNumberProviderPost($userID);
		}
		
		public function getNumberItemPost($userID) {
			return $this->_userDao->getNumberItemPost($userID);
		}
		
		public function addScore($userID, $score) {
			return $this->_userDao->addScore($userID, $score);
		}
		
		public function getUsersOfPage($page) {
			global $ubi;
			
			$from = ($page - 1) * $ubi['SITE']['N_USER_PER_PAGE'];
			$to = $from +  $ubi['SITE']['N_USER_PER_PAGE'];
			
			return $this->_userDao->getUsersFromTo($from, $to);
		}
		
		public function updateMariageStatus($user, $coupleInvitation) {
			global $ubi;
			
			$coupleUserID = $this->isExistedByUserName($user->getCoupleUserName());
			
			if (isset($coupleUserID)) {
				$this->updateUser($user);
				
				$receiver = $this->_userDao->getUser($coupleUserID);
				$linkSenderID = $ubi['SERVER']['SITE_ROOT'] . 'index.php?view&type=user&userid=' + $user->getUserID();
				$linkDelete = $ubi['SERVER']['SITE_ROOT'] . 'index.php?remove&type=coupleInvitation&coupleid=' + $coupleUserID + '&deleteCode=' + $coupleInvitation->getDeleteCode();
				$subject = sprintf('Lời đề nghị từ thành viên %s (%s)', $user->getFirstName() + ' ' + $user->getLastName(), $user->getUserName());
				$message = 'Chào bạn, ' . $receiver->getFirstName() . ' ' . $receiver->getLastName()
					. 'Bạn <a href="' . $linkSenderID . '">' . $user->getUserName() 
					. '<\/a> vừa cập nhật bạn trạng thái tình cảm với lời nhắn : <br \/>'
					. $coupleInvitation->getMessage()  
					. '<br \/>. Nếu bạn không đồng ý với cập nhật của %s hãy link vào link '
					. '<a href="' . $linkDelete . '" \/>';
				
				$to = $receiver->getEmail();
				GeneralFunctions::ubiMail($to, $subject, $message);
				
				$coupleInvitation->setCoupleID($coupleUserID);
				$this->_coupleInvitationDao->addCoupleInvitation($coupleInvitation);
				
				$update = new UpdateModel();
				$update->setIndicteeID($coupleUserID);
				$update->setLink("index.php?view&type=user&userid=" . $user->getUserID());
				$name = $user->getCoupleUserName();
				
				if ($user->getCoupleNickName() != null) {
					$name = $user->getCoupleNickName();
				}
				$update->setName($name);
				$update->setUpdateType($ubi['UPDATE']['MAKE_COUPLE']);
				$update->setUserID($user->getUserID());
				
				$this->_updateBus->addUpdate($update);
			} else {
				$this->_userDao->updateUser($user);
			}	
		}
		
		public function removeCoupleInvitation($userID, $receiverID, $deleteCode) {
			if ($this->_coupleInvitationDao->removeCoupleInvitation($userID, $deleteCode)) {
				$sender = $this->_userDao->getUser($userID);
				$receiver = $this->_userDao->getUser($receiverID);
				
				$toReceiver = $receiver->getEmail();
				$subReceiver = 'Xóa bỏ thông tin bạn trong bảng cập nhật trạng thái tình cảm';
				$messageReceiver = sprintf('Chào bạn, <br /> Hệ thống đã xóa bỏ thông tin bạn trong bảng cập nhật trạng thái tình cảm với thành viên %s', 
					$ubi['SERVER']['SITE_ROOT'] + 'index.php?view&type=user&userid=' + $userID);
				GeneralFunctions::ubiMail($toReciver, $subReceiver, $messageReceiver);

				$toSender = $sender->getEmail();
				$subSender = 'Cập nhật thông tin trong trạng thái tình cảm';
				$mssageSender = sprintf('CHào bạn %s<br />' 
					+ 'Bạn %s không đồng ý sự cập nhật trạng thái tình cảm của bạn nên sự cập nhật vừa rồi đã được xóa khỏi hệ thống', 
					$sender->getUserName(), $sender->getUserName());
				GeneralFunctions::ubiMail($toSender, $subSender, $messageSender);

				$sender->setCoupleNickName(null);
				$sender->setCoupleUserName(null);
				$sender->setMariageStatus(null);
				
				$this->_userDao->updateUser($sender);
			}
		}
	} 
?>